package com.example.foodproject.controller;

import com.example.FoodProject.bean.Comments;
import com.example.FoodProject.dao.CommentsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/comment")
public class CommentsController {

    @Autowired
    CommentsDao dao;

    @RequestMapping("/list/{foodid}")
    @ResponseBody
    public Map<String,Object> list(@PathVariable(name = "foodid") Integer foodid){
        Comments comments = new Comments();
        comments.setFoodid(foodid);
        List<Comments> list = dao.findAll(Example.of(comments));
        Map<String,Object> map = new HashMap<>();
        if (list!=null&&list.size()!=0){
            map.put("success",true);
            map.put("message","成功");
            map.put("list",list);
        }else{
            map.put("success",false);
            map.put("message","失败");
        }
        return map;
    }


    @RequestMapping("/add")
    @ResponseBody
    public Map<String,Object> add(@RequestBody Comments comments){
        Comments comments1 = dao.saveAndFlush(comments);
        Map<String,Object> map = new HashMap<>();
        if (comments1!=null){
            map.put("success",true);
            map.put("message","成功");
            map.put("data",comments1);
        }else{
            map.put("success",false);
            map.put("message","失败");
        }
        return map;
    }


    @RequestMapping("/findone/{id}")
    @ResponseBody
    public Map<String,Object> findone(@PathVariable(name = "id") Integer id){
        Comments comments = dao.findOne(Example.of(new Comments(id))).orElse(null);
        Map<String,Object> map = new HashMap<>();
        if (comments!=null){
            map.put("success",true);
            map.put("message","成功");
            map.put("data",comments);
        }else{
            map.put("success",false);
            map.put("message","失败");
        }
        return map;
    }

    @RequestMapping("/findByFoodId/{id}")
    @ResponseBody
    public Map<String,Object> findByFoodId(@PathVariable(name = "id") Integer foodid){
        List<Comments> list = dao.findByFoodId(foodid, "desc");
        Map<String,Object> map = new HashMap<>();
        if (list!=null&&list.size()>0){
            map.put("success",true);
            map.put("message","成功");
            map.put("data",list);
        }else{
            map.put("success",false);
            map.put("message","失败");
        }
        return map;
    }
    

}
